package com.example.dao.impl;

import com.example.dao.UserDao;
import com.example.entity.User;
import com.example.util.DBUtil;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    /**
     * 通过用户名和密码查询是否有一个这样一个用户
     * 用户名和密码是存放在user对象中的
     * @param connection
     * @param user 返回user对象即查询到，返回null证明用户就不存在
     * @return
     * @throws SQLException
     */
    @Override
    public User getLoginUser(Connection connection, User user)
            throws SQLException {
        String sql = "select username from t_use " +
                "where username = ? and password = ?";
        Object[] params = {user.getUsername(), user.getPassword()};
        ResultSet rs = DBUtil.query(connection, sql, params);
        if (!rs.next()) {
            // 用户不存在就置为空
            user = null;
        }
        return user;
    }

    @Override
    public boolean getUserByUsername(Connection connection,
                                     String username)
            throws SQLException {
        String sql = "select id from t_user where username = ?";
        Object[] params = {username};
        ResultSet rs = DBUtil.query(connection, sql, params);
        boolean exist = rs.next();
        DBUtil.closeResultSet(rs);
        return exist;
    }

    @Override
    public int insertUser(Connection connection, User user) throws SQLException {
        Date date = new Date();
        String created = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(date);
        String sql = "insert into t_user(username, password, created) values(?, ?, ?)";
        Object[] params = {user.getUsername(), user.getPassword(), created};
        return DBUtil.execute(connection, sql, params);
    }
}
